#!/bin/bash

# 记录日志
log_file="/tmp/deploy_$(date +%s).log"
exec > >(tee "$log_file") 2>&1
echo "===== 部署开始: $(date) ====="

# 1. 进入工作目录
cd /var/www/temp/esp32-h5 || {
    echo "错误: 无法进入工作目录"
    ls -la /var/www/temp
    exit 1
}

# 2. 设置环境变量
export PATH="/usr/local/bin:$PATH"
echo "更新后的 PATH: $PATH"

# 3. 检查环境
echo "Node.js 版本: $(node -v)"
echo "npm 版本: $(npm -v)"

# 4. 安装依赖
echo "===== 安装依赖 ====="
npm install || {
    echo "依赖安装失败"
    exit 2
}

# 5. 构建应用
echo "===== 构建应用 ====="
npm run build || {
    echo "构建失败"
    exit 3
}

# 6. 部署文件
DEPLOY_DIR="/var/www/sep32-server/public/"
echo "部署到: $DEPLOY_DIR"
mkdir -p "$DEPLOY_DIR"
cp -a build/* "$DEPLOY_DIR/"

# 7. 重启服务
echo "===== 重启服务 ====="
cd /var/www/sep32-server
yarn install || {
    echo "依赖安装失败"
    exit 4
}
pm2 restart sep32-server || {
    echo "首次启动服务..."
    pm2 start ecosystem.config.js
}

echo "===== 部署成功: $(date) ====="

